<?php
class Rating extends MY_Controller {
    /**
    * Responsable for auto load the model
    * @return void
    */
   public function __construct(){
		parent::__construct();
		// $this->load->model('users_m', 'users');
		// $this->load->model('canhan_m', 'canhan');				
		// $this->load->helper('util');
   }
	
	function index(){
		if($this->input->is_ajax_request()){
			$id	=	$this->input->post('id');
			$type	=	$this->input->post('type');
			$value	=	$this->input->post('value');					
			if(!$id || !$type)
				echo "Ajax fail";
			else{									
				$this->load->model('rating_m', 'rating');
				$id	= 	preg_replace("/[^0-9]/", "", $id);
				$value=	preg_replace("/[^0-9]/", "", $value);
				$ip 	=	$this->input->ip_address();
				if($rated	=	$this->session->userdata('rated'))	
					if(isset($rated[$type.$id])){
						echo json_encode(array(
							'status'		=>	'fail',
							'mesage'		=>	'Đã bình chọn'
						));
						die;
					}
				switch($type){
					case	'CN':
						$data['id']		=	$id;
						$data['type']	=	'CN';
						$data['value']	=	$value;
						$data['ip']		=	$ip;
						if($obj	=	$this->rating->save($data)){
							$rated	=	$this->session->userdata('rated');
							if(!$rated) $rated = array();
							$rated[$type.$id] = $ip;
							$this->session->set_userdata('rated', $rated);
							$rat	=	round($obj->total_value/$obj->total_votes,2);
							ob_start();
							for($k=1; $k<6; $k++){
								if($rat+0.5	> $k)	
									$class="star_".$k." ratings_stars ratings_vote";
								else 
									$class="star_".$k." ratings_stars ratings_blank";
								echo '<div class="'.$class.'"></div>';
							}
						?>
							<input type="hidden" class="ratingType" value="canhan"/>
							<div class="total_votes">
								<span class="voted">&nbsp;&nbsp;&nbsp;&nbsp;<strong><?=$rat?></strong>/5 (<?=$obj->total_votes?> votes)</span>
							</div>
						<?php
							$html	=	ob_get_clean();
							echo json_encode(array(
								'status'		=>	'success',
								'html'		=>	$html
							));
						}
					break;
				}
			}
		}else		
			echo "Not ajax";
		die;
 	}	
 }